package com.ceba.test.modules.regist.dao;


import com.ceba.base.web.dao.IBaseDao;
import com.ceba.test.modules.regist.entity.Enterprise;

import abc.ID;
import abc.data.DataRow;
import abc.data.DataTable;
import abc.data.Sql;
import abc.data.SqlSessionManager;
import abc.data.store.IStore;
import abc.data.store.StoreManager;
import abc.object.IObject;
import abc.object.XObject;

public class EnterpriseDao extends IBaseDao {
	

	/**
	 * 添加一条记录
	 * @return
	 */
	public Boolean add(Enterprise enterprise) throws Exception{
		IStore store = StoreManager.create("enterprise");
		IObject object = new XObject("enterprise");
		object.put("ID",ID.getGuid());
		object.put("ENTERPRISE_NAME",enterprise.getEnterpriseName());
		object.put("ENTERPRISE_EMAIL", enterprise.getEnterpriseEmail());
		object.put("ENTERPRISE_PHONE",enterprise.getEnterprisePhone());
		object.put("ACTIVATE_CODE",enterprise.getActivateCode());
		object.setCreateTime();
		object.setCreateUser();
		if(store.insert(object)>0){
			return true;	
		}
		return false;
	}
	
	
	/**
	 * 删除一条数据
	 * @param id 数据id
	 * @return
	 */
	public Boolean delete(String id) throws Exception{
		
		Sql sql = new Sql("DELETE FROM enterprise WHERE ID = ?");
		sql.addParameter(id);
		return SqlSessionManager.execute(sql);
	}
	
	public Boolean deleteByName(String enterpriseName) throws Exception{
		Sql sql = new Sql("DELETE FROM enterprise WHERE ENTERPRISE_NAME = ?");
		sql.addParameter(enterpriseName);
		return SqlSessionManager.execute(sql);
	}
	
	private void copyDrToEnterprise(DataRow dr,Enterprise enter ){
		enter.setId(dr.getString("ID"));
		enter.setEnterpriseName(dr.getString("ENTERPRISE_NAME"));
		enter.setEnterpriseEmail(dr.getString("ENTERPRISE_EMAIL"));
		enter.setEnterprisePhone(dr.getString("ENTERPRISE_PHONE"));
	}
	/**
	 * @return 公司名称唯一
	 */
	public Enterprise getEnterprise(String user,String email,String phone) throws Exception{
		Sql sql = new Sql("SELECT * FROM enterprise WHERE ENTERPRISE_NAME=?");
		sql.addParameter(user);
		DataTable dt= SqlSessionManager.getDataTable(sql);
		if(dt !=null && dt.getRowCount() >0){
			Enterprise enter = new Enterprise();
			DataRow dr = dt.getRow(0);
			copyDrToEnterprise(dr,enter);
			return enter;
		}
		return null;
	}
	
	public boolean checkExistByNameAndActivateCode(String enterpriseName,String code) throws Exception{
		long l= SqlSessionManager.getCount(" enterprise WHERE ENTERPRISE_NAME='"+enterpriseName
					+"' AND ACTIVATE_CODE='"+code+"'");
		if(l > 0){
			return true;
		}
		return false;
	}


	public Enterprise getEnterpriseByName(String enterpriseName)throws Exception {
		Sql sql = new Sql("SELECT * FROM enterprise WHERE ENTERPRISE_NAME=?");
		sql.addParameter(enterpriseName);
		DataTable dt= SqlSessionManager.getDataTable(sql);
		if(dt !=null && dt.getRowCount() >0){
			Enterprise enter = new Enterprise();
			DataRow dr = dt.getRow(0);
			copyDrToEnterprise(dr,enter);
			return enter;
		}
		return null;
	}
	
	
	

}
